<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 角色及角色组类
 * @package  htdocs
 * @subpackage  quanliadmin
 * @author   allen.qiang
 * @version 1.0
 */

class sysRole {

    /**
     * 查询角色组信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchRoleGroup( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //角色组ID
        if (isset($arg_array['roleGroupID']) && is_numeric($arg_array['roleGroupID'])) {
            $sql .= ' AND roleGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['roleGroupID'];
        }

        //角色组名
        if (isset($arg_array['roleGroupName']) && !empty($arg_array['roleGroupName'])) {
            $sql .= ' AND roleGroupName = ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['roleGroupName'] . '%';
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM user_rolegroup' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM user_rolegroup' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    $item_array[] = array(
                        'uuid' => $item->uuid,
                        'roleGroupID' => $item->roleGroupID,
                        'roleGroupName' => $item->roleGroupName,
                        'memo' => $item->memo
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 新增或修改角色组
     * @param array $arg_array 角色组参数信息
     * @return array
     */
    public function editRoleGroup( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array['roleGroupID'], $arg_array['roleGroupName'], $arg_array['operator'], $arg_array['memo'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (!is_numeric($arg_array['roleGroupID'])) {
            $arg_array['roleGroupID'] = 0;
        }

        if (empty($arg_array['roleGroupName'])) {
            return array( 'code' => 400, 'message' => '请输入角色组名称' );
        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            $role_group_obj = new entity('user_rolegroup');
            if ($arg_array['roleGroupID'] > 0) {
                $role_group_obj->roleGroupID = $arg_array['roleGroupID'];
                if (!$G_SHOP->DBCA->fetch($role_group_obj)) {
                    throw new Exception('角色组信息没有找到', 404);
                }

                //更新角色表中角色组名称
                $update_sql = 'UPDATE user_role SET roleGroupName = ? WHERE roleGroupID = ?';
                $G_SHOP->DBCA->stmt_query($update_sql, 'si', convertVar($arg_array['roleGroupName']), $arg_array['roleGroupID']);

            } else {
                $role_group_obj->creator = $arg_array['operator'];
            }
            $role_group_obj->roleGroupName = convertVar($arg_array['roleGroupName']);
            $role_group_obj->memo = convertVar($arg_array['memo']);
            $G_SHOP->DBCA->save($role_group_obj);

            $G_SHOP->DBCA->commit();

            if ($arg_array['roleGroupID'] > 0) {
                return array( 'code' => 200, 'message' => '角色组修改成功' );
            } else {
                return array( 'code' => 200, 'message' => '角色组新增成功' );
            }

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询角色信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchRole ( &$arg_array ) {

        global $G_SHOP;

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //角色ID
        if (isset($arg_array['roleID']) && is_numeric($arg_array['roleID'])) {
            $sql .= ' AND roleID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['roleID'];
        }

        //角色名
        if (isset($arg_array['roleName']) && !empty($arg_array['roleName'])) {
            $sql .= ' AND roleName = ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['roleName'] . '%';
        }

        //角色组ID
        if (isset($arg_array['roleGroupID']) && is_numeric($arg_array['roleGroupID'])) {
            $sql .= ' AND roleGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['roleGroupID'];
        }
        if (isset($arg_array['s_roleGroupID']) && is_numeric($arg_array['s_roleGroupID'])) {
            $sql .= ' AND roleGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['s_roleGroupID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && is_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM user_role' . $sql;
                $count_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM user_role' . $sql;
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array) {
                return null;
            }

            foreach ($temp_item_array as &$item) {

                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'roleID' => $item->roleID,
                    'roleName' => $item->roleName,
                    'roleGroupID' => $item->roleGroupID,
                    'roleGroupName' => $item->roleGroupName,
                    'useFlg' => $item->useFlg,
                    'memo' => $item->memo
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 新增/修改角色
     * @param array $arg_array 角色参数数组
     * @return array
     */
    public function editRole( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array['roleGroupID'], $arg_array['roleID'], $arg_array['operator'], $arg_array['memo'], $arg_array['roleName'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (!is_numeric($arg_array['roleID'])) {
            $arg_array['roleID'] = 0;
        }

        if ($arg_array['roleGroupID'] <= 0) {
            return array( 'code' => 400, 'message' => '请选择角色组' );
        }

        if (empty($arg_array['roleName'])) {
            return array( 'code' => 400, 'message' => '角色名称不能为空' );
        }

        try {

            //查询角色组信息
            $t_arg_array = array(
                'roleGroupID' => $arg_array['roleGroupID']
            );
            $role_group_array = $this->searchRoleGroup( $t_arg_array );
            if (!$role_group_array) {
                throw new Exception('角色组信息没有找到', 404);
            }

            $role_obj = new entity('user_role');
            if ($arg_array['roleID'] > 0) {
                $role_obj->roleID = $arg_array['roleID'];
                if (!$G_SHOP->DBCA->fetch($role_obj)) {
                    throw new Exception('角色信息没有找到', 404);
                }
            } else {
                $role_obj->creator = $arg_array['operator'];
            }
            $role_obj->roleName = convertVar($arg_array['roleName']);
            $role_obj->roleGroupID = $role_group_array[0]['roleGroupID'];
            $role_obj->roleGroupName = $role_group_array[0]['roleGroupName'];
            $role_obj->useFlg = 1;
            $role_obj->memo = convertVar($arg_array['memo']);
            $G_SHOP->DBCA->save($role_obj);

            if ($arg_array['roleID'] > 0) {
                return array( 'code' => 200, 'message' => '角色修改成功' );
            } else {
                return array( 'code' => 200, 'message' => '角色新增成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询角色权限信息
     * @param int $roleID
     * @return array
     */
    public function searchRolePermission( $roleID ) {

        global $G_SHOP;

        $search_sql = 'SELECT * FROM user_rolepermission WHERE roleID = ?';
        $permission_array = &$G_SHOP->DBCA->stmt_query($search_sql, 'i', $roleID);

        if (!$permission_array) {
            return null;
        }

        foreach($permission_array as &$permission) {
            $item_array[$permission->permissionID] = 1;
        }

        return $item_array;

    }

    /**
     * 添加角色权限
     * @param array $arg_array
     * @return array
     */
    public function editRolePermission( $arg_array ) {

        global $G_SHOP;

        quanli_require('module/base/project/permission.class.php');

        if (!isset($arg_array['operator'], $arg_array['permission_box'], $arg_array['roleID']) || empty($arg_array['operator'])
            || !is_array($arg_array['permission_box']) || !is_numeric($arg_array['roleID'])) {
            return array( 'code' => 400, 'message' => '参数错误1' );
        }

        if (empty($arg_array['permission_box'])) {
            return array( 'code' => 400, 'message' => '请选择权限' );
        }

        //实例权限类
        $permission = new permission();

        try {

            $G_SHOP->DBCA->beginTransaction();

            //查询角色信息
            $r_arg_array = array(
                'roleID' => $arg_array['roleID']
            );
            $role_array = $this->searchRole( $r_arg_array );
            if (!$role_array) {
                throw new Exception('角色信息没有找到', 404);
            }

            //删除已有的角色权限
            $delete_sql = 'DELETE FROM user_rolepermission WHERE roleID = ' . $arg_array['roleID'];
            $G_SHOP->DBCA->stmt_query($delete_sql);

            //保存新的权限

            $insert_sql = 'INSERT INTO user_rolepermission (uuid,timeStamp,creator,createTime,roleID,permissionGroupID,permissionID) VALUES ';
            $insert_num = 0;
            $datetime = date(G_DEFAULT_DATETIME_FORMAT);

            foreach($arg_array['permission_box'] as &$permissionID) {

                //查询权限信息
                $p_arg_array = array(
                    'permissionID' => $permissionID
                );
                $permission_array = $permission->searchPermission( $p_arg_array );
                if (!$permission_array) {
                    continue;
                }

                if ($insert_num > 0) {
                    $insert_sql .= ',';
                }
                $insert_sql .= sprintf('("%s", "%s", "%s", "%s", %s, %s, %s)', make_uuid(), $datetime, $arg_array['operator'], $datetime,
                    $arg_array['roleID'], $permission_array[0]['permissionGroupID'], $permission_array[0]['permissionID']);

                ++$insert_num;

            }

            if ($insert_num == 0) {
                throw new Exception('请选择权限', 400);
            }

            $G_SHOP->DBCA->stmt_query($insert_sql);

            $G_SHOP->DBCA->commit();

            return array( 'code' => 200, 'message' => '角色权限保存成功' );

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 批量删除角色信息
     * @param array $arg_array 角色组参数数组
     * @return array
     * @throws Exception
     */
    public function deleteRole ( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array) || !is_array($arg_array) || empty($arg_array)) {
            return array( 'code' => 400, 'message' => '请选择要删除的角色' );
        }

        try {

            foreach($arg_array as &$roleID) {

                //检查角色信息
                $role_obj = new entity('user_role');
                $role_obj->roleID = $roleID;
                if (!$G_SHOP->DBCA->fetch($role_obj)) {
                    continue;
                }
                $G_SHOP->DBCA->delete( $role_obj );

            }

            return array( 'code' => 200, 'message' => '角色删除成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 批量删除角色组信息
     * @param array $arg_array 角色组参数数组
     * @return array
     * @throws Exception
     */
    public function deleteRoleGroup( $arg_array ) {

        global $G_SHOP;

        if (!isset($arg_array) || !is_array($arg_array) || empty($arg_array)) {
            return array( 'code' => 400, 'message' => '请选择要删除的角色组' );
        }

        try {

            foreach($arg_array as &$roleGroupID) {

                //检查角色组信息
                $role_group_obj = new entity('user_rolegroup');
                $role_group_obj->roleGroupID = $roleGroupID;
                if (!$G_SHOP->DBCA->fetch($role_group_obj)) {
                    continue;
                }
                $G_SHOP->DBCA->delete( $role_group_obj );

            }

            return array( 'code' => 200, 'message' => '角色组删除成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

}